"""
Case Type   : cm_ctl
Case Name   : 执行cm_ctl pause后,执行cm_ctl stop -n 主
Create At   : 2023/03/24
Owner       : opentestcase012
Description :
    1.执行cm_ctl pause;
    2.停止主节点;
    3.查看集群状态;
    4.恢复集群状态;
Expect      :
    1.暂停成功
    2.执行成功
    3.dn主Down,其他节点dn状态异常
    4.恢复成功
History     :
"""
import os
import time
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

primary_sh = CommonSH('PrimaryDbUser')


# @unittest.skipIf(2 != primary_sh.get_node_num(), '非1+2环境不执行')
class DefinedResource(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')

    def test_cm(self):
        text = '----step1:执行cm_ctl pause; expect:暂停成功----'
        self.log.info(text)
        cm_ctl_res = self.primary_sh.exec_cm_ctl('pause')
        self.assertIn(self.constant.cm_pause_success_msg, cm_ctl_res,
                      '执行失败:' + text)

        text = '----step2:停止主节点; expect:执行成功----'
        self.log.info(text)
        cm_ctl_res = self.primary_sh.exec_cm_ctl('switchover', '-a')
        self.assertIn(self.constant.cm_switchover_success_msg, cm_ctl_res,
                      '执行失败:' + text)
        cm_ctl_res = self.primary_sh.exec_cm_ctl('stop', '-n 1')
        self.assertIn(self.constant.cm_stop_node_success_msg, cm_ctl_res,
                      '执行失败:' + text)

        time.sleep(10)
        text = '----step3:查看集群状态; expect:dn主Down,其他节点dn状态异常----'
        self.log.info(text)
        cm_ctl_res = self.primary_sh.exec_cm_ctl('query', '-Civ')
        self.assertIn('pausing         : Yes', cm_ctl_res, '执行失败:' + text)
        self.assertIn('P Down    Unknown', cm_ctl_res, '执行失败:' + text)
        self.assertEqual(2,
                         cm_ctl_res.count('Standby Need repair'),
                         '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        text = '----step4:恢复集群状态; expect:执行成功----'
        self.log.info(text)
        cm_ctl_res1 = self.primary_sh.exec_cm_ctl('resume')
        cm_ctl_res2 = self.primary_sh.exec_cm_ctl('start')
        cm_ctl_res3 = self.primary_sh.exec_cm_ctl('switchover', '-a')
        time.sleep(10)
        cm_ctl_res4 = self.primary_sh.exec_cm_ctl('query', '-Civ')
        self.assertIn(self.constant.cm_resume_success_msg, cm_ctl_res1,
                      '执行失败:' + text)
        self.assertIn(self.constant.cm_start_success_msg, cm_ctl_res2,
                      '执行失败:' + text)
        self.assertIn(self.constant.cm_switchover_success_msg, cm_ctl_res3,
                      '执行失败:' + text)
        self.assertIn(self.constant.CLUSTER_NORMAL_MSG, cm_ctl_res4,
                      "执行失败:" + text)
        self.log.info(f'----{os.path.basename(__file__)} finish----')
